/*
 * $Id: ColorUtils.java 30 2011-05-24 02:09:39Z rob.whelan@patientsknowbest.com $ 
 */
package com.representqueens.util;

/*
 * 
 * Copyright 2006 Larry Ogrodnek
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.awt.Color;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

/**
 * Utility methods for parsing Strings into Color Objects.
 * 
 * @author Larry Ogrodnek <larry@cheesesteak.net>
 * @version $Revision: 30 $ $Date: 2011-05-24 02:09:39 +0000 (Tue, 24 May 2011) $
 */
public final class ColorUtils {
    private ColorUtils() {
    }

    /**
     * Parse a String into a Color.
     * 
     * This method will accept either a color name (a field name from
     * {@link Color}, case insensitive e.g. "red"), or a HTML hex color string
     * (e.g. "#ff0000" or "ff0000" -- # is added if needed -- for Color.RED).
     * 
     * @param s
     *            String to parse for color name or color number.
     * @return Color for s.
     */
    public static Color parseColor(final String s) {
    	Color color = null;

    	if (!StringUtils.isEmpty(s)) {
    		String withHash = s.startsWith("#") ? s : "#" + s;
    		try {
    			color = Color.decode(withHash);
    		} catch (final NumberFormatException nfe) {
    			color = colorByField(s);
    		}
    	}

    	return color;
    }

    private static Color colorByField(final String _s) {
    	final Field[] fields = Color.class.getFields();

    	final String s = _s.toLowerCase();

    	try {
    		for (final Field f : fields) {
    			if (f.getName().toLowerCase().equals(s)) {
    				final int mod = f.getModifiers();
    				if (Modifier.isStatic(mod) && Modifier.isPublic(mod)
    						&& Color.class.equals(f.getType())) {
    					return (Color) f.get(null);
    				}
    			}
    		}
    	} catch (final IllegalAccessException iae) {
    		// ?
    		iae.printStackTrace();
    	}

    	return null;
    }
}
